package com.netdevsdk.demo.playback.play;

import java.io.File;

import javax.swing.JOptionPane;

import com.sun.jna.ptr.LongByReference;

import com.netdevsdk.demo.NetDemo;
import com.netdevsdk.demo.util.Common;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_E_DOWNLOAD_SPEED_E;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_MEDIA_FILE_FORMAT_E;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_PLAYBACKCOND_S;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_PLAYBACKINFO_S;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_VOD_PLAY_CTRL_E;

/**
 * 
 * @introduction Download Record
 * @description Support NVR/VMS
 */
public class DownloadRecord {
    /**
     * 
     * @introduction Download Record
     * @description Calling the interface of NETDEV_GetFileByTime to download the record by time
     *
     */
    public static void startDownload() {
        if(null == NetDemo.lpUserID)
        {
            JOptionPane.showMessageDialog(null, "Please Login device first. error code"+NetDemo.netdevsdk.NETDEV_GetLastError());
            return;
        }
        if(NetDemo.RecordTable.getSelectedRow()<0) {
            JOptionPane.showMessageDialog(null, "No file,please choose a file");
            return;
        }

        NetDemo.jButtonStartdownload.setEnabled(false);
        int row=NetDemo.RecordTable.getSelectedRow();
        String Beginstr=(String)NetDemo.RecordTable.getValueAt(row, 0);
        String Endstr=(String)NetDemo.RecordTable.getValueAt(row, 1);
        String strSeparator = File.separator;
        NetDemo.strRecordPath = System.getProperty("user.dir").replaceAll("%20"," ") + strSeparator+"Record"+strSeparator+"DownloadFile" + Common.timeStamp()+ "_D"+NetDemo.ChannelID;    
        NETDEV_PLAYBACKCOND_S pstPlayBackCond = new NETDEV_PLAYBACKCOND_S();
        pstPlayBackCond.dwChannelID = NetDemo.ChannelID;
        pstPlayBackCond.dwDownloadSpeed = NETDEV_E_DOWNLOAD_SPEED_E.NETDEV_DOWNLOAD_SPEED_EIGHT;
        pstPlayBackCond.tBeginTime = Common.date2TimeStamp(Beginstr, NetDemo.DateFormat);
        pstPlayBackCond.tEndTime = Common.date2TimeStamp(Endstr, NetDemo.DateFormat);
        
        NetDemo.lpDownloadHandle = NetDemo.netdevsdk.NETDEV_GetFileByTime(NetDemo.lpUserID, pstPlayBackCond, NetDemo.strRecordPath, NETDEV_MEDIA_FILE_FORMAT_E.NETDEV_MEDIA_FILE_MP4);
        if(null != NetDemo.lpDownloadHandle){
            NetDemo.DownloadProgress.setMaximum((int)pstPlayBackCond.tEndTime);
            NetDemo.DownloadProgress.setMinimum((int)pstPlayBackCond.tBeginTime);
            Thread singledownloadThread=new Thread(new Runnable() {
                @Override
                public void run() {
                    int nCount = 0;
                    long getFileTime=0;
                    int failCount=0;
                    while(true)
                    {
                        LongByReference PlayTime = new LongByReference();
                        boolean bRet = NetDemo.netdevsdk.NETDEV_PlayBackControl(NetDemo.lpDownloadHandle, NETDEV_VOD_PLAY_CTRL_E.NETDEV_PLAY_CTRL_GETPLAYTIME, PlayTime);
                        if(bRet){
                            long lTime = PlayTime.getValue();
                            NetDemo.DownloadProgress.setValue((int)lTime);
                            if(lTime!=getFileTime) {
                                getFileTime=lTime;
                                failCount=0;
                            }else {
                                failCount++;
                                if(failCount==5) {
                                    NetDemo.netdevsdk.NETDEV_StopGetFile(NetDemo.lpDownloadHandle);
                                    NetDemo.DownloadProgress.setValue(NetDemo.DownloadProgress.getMaximum());
                                    NetDemo.lpDownloadHandle = null;
                                    break;
                                }
                            }
                        }
                        else{
                            nCount++;
                            System.out.println("Get playback time failed");
                        }
                        if((long)NetDemo.DownloadProgress.getMaximum() == PlayTime.getValue() || PlayTime.getValue() > (long)NetDemo.DownloadProgress.getMaximum()
                                || nCount>3){
                            NetDemo.netdevsdk.NETDEV_StopGetFile(NetDemo.lpDownloadHandle);
                            NetDemo.DownloadProgress.setValue(NetDemo.DownloadProgress.getMaximum());
                            NetDemo.lpDownloadHandle = null;
                            NetDemo.jButtonStartdownload.setEnabled(true);
                            break;
                        }
                        try{
                            Thread.sleep(700);
                        }catch(InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            });
            NetDemo.singleLiveThread.execute(singledownloadThread);
        }
    }

    /**
     * 
     * @introduction Download Record by name
     * @description Calling the interface of NETDEV_GetFileByName to download the record by time
     *
     */
    public static void startDownloadByName() {
        if(null == NetDemo.lpUserID)
        {
            JOptionPane.showMessageDialog(null, "Please Login device first. error code"+NetDemo.netdevsdk.NETDEV_GetLastError());
            return;
        }
        if(NetDemo.RecordTable.getSelectedRow()<0) {
            JOptionPane.showMessageDialog(null, "No file,please choose a file");
            return;
        }
        
        NetDemo.jButtonStartdownloadByName.setEnabled(false);
        String strSeparator = File.separator;
        NetDemo.strRecordPath = System.getProperty("user.dir").replaceAll("%20"," ") + strSeparator +"Record"+strSeparator+"DownloadFile" + String.valueOf(Common.timeStamp())+ "_D"+NetDemo.ChannelID;
        NETDEV_PLAYBACKINFO_S pstPlayBackCond = new NETDEV_PLAYBACKINFO_S();
        int row=NetDemo.RecordTable.getSelectedRow();
        /* 获取文件名 */
        String str=(String)NetDemo.RecordTable.getValueAt(row, 2);
        System.arraycopy(str.getBytes(), 0, pstPlayBackCond.szName, 0, str.getBytes().length);
        String Beginstr=(String)NetDemo.RecordTable.getValueAt(row, 0);
        String Endstr=(String)NetDemo.RecordTable.getValueAt(row, 1);
        pstPlayBackCond.dwDownloadSpeed = NETDEV_E_DOWNLOAD_SPEED_E.NETDEV_DOWNLOAD_SPEED_EIGHT;
        pstPlayBackCond.tBeginTime =Common.date2TimeStamp(Beginstr, NetDemo.DateFormat);
        pstPlayBackCond.tEndTime = Common.date2TimeStamp(Endstr, NetDemo.DateFormat);
        NetDemo.lpDownloadHandleByName = NetDemo.netdevsdk.NETDEV_GetFileByName(NetDemo.lpUserID, pstPlayBackCond, NetDemo.strRecordPath, NETDEV_MEDIA_FILE_FORMAT_E.NETDEV_MEDIA_FILE_MP4);
        
        if(null != NetDemo.lpDownloadHandleByName){
            NetDemo.DownloadProgress.setMaximum((int)pstPlayBackCond.tEndTime);
            NetDemo.DownloadProgress.setMinimum((int)pstPlayBackCond.tBeginTime);
            Thread singledownloadByNameThread=new Thread(new Runnable() {
                @Override
                public void run() {
                    int nCount = 0;
                    long getFileTime=0;
                    int failCount=0;
                    while(true)
                    {
                        LongByReference PlayTime = new LongByReference();
                        boolean bRet = NetDemo.netdevsdk.NETDEV_PlayBackControl(NetDemo.lpDownloadHandleByName, NETDEV_VOD_PLAY_CTRL_E.NETDEV_PLAY_CTRL_GETPLAYTIME, PlayTime);
                        if(bRet){
                            long lTime = PlayTime.getValue();
                            NetDemo.DownloadProgress.setValue((int)lTime);
                            if(lTime!=getFileTime) {
                                getFileTime=lTime;
                                failCount=0;
                            }else {
                                failCount++;
                                if(failCount==5) {
                                    NetDemo.netdevsdk.NETDEV_StopGetFile(NetDemo.lpDownloadHandleByName);
                                    NetDemo.DownloadProgress.setValue(NetDemo.DownloadProgress.getMaximum());
                                    NetDemo.lpDownloadHandleByName = null;
                                    break;
                                }
                            }
                        }
                        else{
                            nCount++;
                            System.out.println("Get playback time failed");
                        }
                        if((long)NetDemo.DownloadProgress.getMaximum() == PlayTime.getValue() || PlayTime.getValue() > (long)NetDemo.DownloadProgress.getMaximum()
                                || nCount>3){
                            NetDemo.netdevsdk.NETDEV_StopGetFile(NetDemo.lpDownloadHandleByName);
                            NetDemo.DownloadProgress.setValue(NetDemo.DownloadProgress.getMaximum());
                            NetDemo.lpDownloadHandleByName = null;
                            NetDemo.jButtonStartdownloadByName.setEnabled(true);
                            break;
                        }
                        try{
                            Thread.sleep(700);
                        }catch(InterruptedException e){
                            e.printStackTrace();
                        }
                    }

                }
            });
            NetDemo.singleLiveThread.execute(singledownloadByNameThread);
        }
    }

    /**
     * 
     * @introduction Stop download
     * @description Calling the interface of NETDEV_StopGetFile
     *
     */
    public static void stopDownload() {
        NetDemo.jButtonStartdownload.setEnabled(true);
        if(null != NetDemo.lpDownloadHandle){
            NetDemo.netdevsdk.NETDEV_StopGetFile(NetDemo.lpDownloadHandle);
            NetDemo.lpDownloadHandle = null;
            NetDemo.DownloadProgress.setValue(NetDemo.DownloadProgress.getMaximum());
        }else {
            JOptionPane.showMessageDialog(null, "No file is downloading,or you use wrong button.");
        }
    
    }

    /**
     * 
     * @introduction Stop download by name
     * @description Calling the interface of NETDEV_StopGetFile
     *
     */
    public static void stopDownloadByName() {
        NetDemo.jButtonStartdownloadByName.setEnabled(true);
        if(null != NetDemo.lpDownloadHandleByName){
            NetDemo.netdevsdk.NETDEV_StopGetFile(NetDemo.lpDownloadHandleByName);
            NetDemo.lpDownloadHandleByName = null;
            NetDemo.DownloadProgress.setValue(NetDemo.DownloadProgress.getMaximum());
        }else {
            JOptionPane.showMessageDialog(null, "No file is downloading,or you use wrong button.");
        }
    
    }
    
}
